package com.laicunba.event.listener;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.event.FirstBidEvent;
import com.laicunba.event.FriendBuyEvent;
import com.laicunba.event.FriendFirstBuyEvent;
import com.laicunba.event.PaySuccessEvent;
import com.laicunba.event.UserCacheUpdateEvent;
import com.laicunba.event.inner.CacheKey;
import com.laicunba.pojo.FinancingTargetBidDO;
import com.laicunba.pojo.FinancingTargetDO;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.pojo.TemplateDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.FinancingTargetBidService;
import com.laicunba.service.FinancingTargetService;
import com.laicunba.service.MobileMessageService;
import com.laicunba.service.RegistryService;
import com.laicunba.service.TemplateService;
import com.laicunba.service.UserService;
import com.laicunba.service.accounting.RewardBidService;
import com.laicunba.service.activity.FriendBidActivityService;
import com.laicunba.service.mq.ActiveMQMessageFactory;
import com.laicunba.service.mq.ActiveMQService;
import com.laicunba.util.DateUtil;
import com.laicunba.util.StringUtil;

@Component
public class PaySuccessListener implements ApplicationListener<PaySuccessEvent>, ApplicationEventPublisherAware {
	private static final Logger LOG = Logger.getLogger(PaySuccessListener.class);
	private ApplicationEventPublisher applicationEventPublisher;
	@Autowired
	private MobileMessageService mobileMessageService;
	@Autowired
	private TemplateService templateService;
	@Autowired
	private UserService userService;
	@Autowired
	private FinancingTargetService financingTargetService;
	@Autowired
	private FinancingTargetBidService financingTargetBidService;
	@Autowired
	private RegistryService registryService;
	@Autowired
	private RewardBidService rewardBidService;

	@Autowired
	private FriendBidActivityService friendBidActivityService;
	@Autowired
	private ActiveMQService activeMQService;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void onApplicationEvent(PaySuccessEvent event) {
		FinancingTargetBidDO bidDO = (FinancingTargetBidDO) event.getSource();

		//发送清理用户缓存事件
		try{
			UserCacheUpdateEvent  userCacheUpdateEvent = new UserCacheUpdateEvent(new CacheKey(bidDO.getBidUserId()));
			applicationEventPublisher.publishEvent(userCacheUpdateEvent);
		}catch(Exception e){
			LOG.error("clear user cache fail: "+bidDO.getBidUserId());
		}
		
		// send mq
		JSONObject msg = ActiveMQMessageFactory.createUsrPaySuccessMessage(bidDO);
		activeMQService.sendTopics(ActiveMQMessageFactory.CORE_USR_PAY_SUCCESS, msg.toJSONString());

		FinancingTargetDO target = financingTargetService.get(FinancingTargetDO.class, bidDO.getFinancingTargetId());
		TemplateDO templateDO = null;
		Map param = new HashMap();
		if ("SCB".equalsIgnoreCase(bidDO.getType())) {
			templateDO = templateService.findByCodeWidthDefault("SCB_PAY_SUCCESS_NEW");

		} else {
			templateDO = templateService.findByCodeWidthDefault("CPB_PAY_SUCCESS_NEW");
		}
		param.put("buyAmount", bidDO.getBuyAmount().toString());
		param.put("targetName", target.getName());
		param.put("BeginTime", DateUtil.formatDate(bidDO.getBeginProfit()));
		param.put("EndTime", DateUtil.formatDate(bidDO.getEndProfit()));
		String content = templateService.simpleMerge(templateDO.getContent(), param);
		UserDO userDO = userService.get(UserDO.class, bidDO.getBidUserId());
		mobileMessageService.sendMsgAsync(userDO.getMobile(), content);
		// 如果未认证,则给于认证
		if (StringUtil.hasEmpty(userDO.getTrueName(), userDO.getPid()) && StringUtil.isNotEmpty(bidDO.getPayName(), bidDO.getPayPid())) {
			userDO.setTrueName(bidDO.getPayName());
			userDO.setPid(bidDO.getPayPid());
			if (userService.updateSkipCheckOwner(userDO)) {
				LOG.info(String.format("用户[%s]购买成功后,自动认证成功.姓名[%s]身份证号[%s]", userDO.getId(), userDO.getTrueName(), userDO.getPid()));
			} else {
				LOG.warn(String.format("用户[%s]购买成功后,自动认证失败.购买记录ID[%s]", userDO.getId(), bidDO.getId()));
			}

		}

		// 如果认定为首次购买
		boolean isFirstBuy = financingTargetBidService.isFirstBid(bidDO.getBidUserId());
		if (isFirstBuy) {
			try {
				FirstBidEvent firstBidEvent = new FirstBidEvent(bidDO);
				applicationEventPublisher.publishEvent(firstBidEvent);
			} catch (Exception e) {
				LOG.error("首次购买事件出错", e);
			}
		}

		UserDO inviteUser = null;
		if (StringUtil.isNotEmpty(userDO.getInviteFrom())) {
			inviteUser = userService.findInviteUser(bidDO.getBidUserId());
		}
		if (inviteUser != null) {
			try {
				Map source = new HashMap();
				source.put("friendDO", inviteUser);
				source.put("bidDO", bidDO);
				source.put("bidUserDO", userDO);
				
				JSONObject  jmsMsg = 	ActiveMQMessageFactory.createEmptyMessage("FRIEND_BUY");
				jmsMsg.put("bid", bidDO.getId());
				jmsMsg.put("type", "CPB".equalsIgnoreCase(bidDO.getType())?"D":"H");
				jmsMsg.put("buy_amount", bidDO.getBuyAmount());
				jmsMsg.put("rate", bidDO.getAnnualizedRates());
				jmsMsg.put("friend_id", inviteUser.getId());
				jmsMsg.put("friend_mobile", inviteUser.getMobile());
				jmsMsg.put("friend_name", inviteUser.getTrueName());
				jmsMsg.put("buyer_uid", userDO.getId());
				jmsMsg.put("buyer_mobile", userDO.getMobile());
				jmsMsg.put("buyer_name", userDO.getTrueName());
				activeMQService.sendTopics("lcb.core.firend.buy", jmsMsg.toJSONString());
				
				FriendBuyEvent friendBuyEvent = new FriendBuyEvent(source);
				applicationEventPublisher.publishEvent(friendBuyEvent);

				if (isFirstBuy) {
					FriendFirstBuyEvent friendFirstBuyEvent = new FriendFirstBuyEvent(source);
					applicationEventPublisher.publishEvent(friendFirstBuyEvent);
				}

			} catch (Exception e) {
				LOG.error("好友购买事件处理出错", e);
			}
		}
		if ("CPB".equalsIgnoreCase(bidDO.getType())) {
			if (inviteUser != null) {
				RegistryDO registryDO = registryService.get(RegistryDO.class, "act.invite.firstbuy.open");
				if (registryDO != null && "true".equalsIgnoreCase(registryDO.getVal())) {
					try {
						friendBidActivityService.doActivity(userDO, inviteUser, bidDO);
					} catch (Exception e) {
						LOG.error("好友购买送体验金活动出错", e);
					}
				}
			}
		}

	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.applicationEventPublisher = applicationEventPublisher;
	}

}
